# -*- coding: utf-8 -*-
# Author   : ZhangQing
# Time     : 2025-08-14
# File     : file_service.py
# Project  : codebuddy_craft
# Desc     : 文件服务

import os
import asyncio
from typing import Dict, Any, List, Optional, BinaryIO
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, update, delete
from datetime import datetime

from backend.models.file import File
from backend.models.project import Project

class FileService:
    """
    文件服务
    
    处理文件的创建、读取、更新和删除操作
    """
    
    @staticmethod
    async def create_file(
        db: AsyncSession,
        project_id: str,
        path: str,
        content: str,
        user_id: str
    ) -> File:
        """
        创建文件
        
        在指定项目中创建新文件
        """
        # 检查项目是否存在
        result = await db.execute(select(Project).where(Project.id == project_id))
        project = result.scalar_one_or_none()
        
        if not project:
            raise ValueError(f"项目不存在: {project_id}")
        
        # 检查文件是否已存在
        result = await db.execute(
            select(File).where(
                File.project_id == project_id,
                File.path == path
            )
        )
        existing_file = result.scalar_one_or_none()
        
        if existing_file:
            raise ValueError(f"文件已存在: {path}")
        
        # 创建新文件
        new_file = File(
            project_id=project_id,
            path=path,
            content=content,
            created_by=user_id,
            updated_by=user_id
        )
        
        db.add(new_file)
        await db.commit()
        await db.refresh(new_file)
        
        return new_file
    
    @staticmethod
    async def get_file(
        db: AsyncSession,
        file_id: str
    ) -> Optional[File]:
        """
        获取文件
        
        通过ID获取文件
        """
        result = await db.execute(select(File).where(File.id == file_id))
        return result.scalar_one_or_none()
    
    @staticmethod
    async def get_file_by_path(
        db: AsyncSession,
        project_id: str,
        path: str
    ) -> Optional[File]:
        """
        通过路径获取文件
        
        在指定项目中查找文件
        """
        result = await db.execute(
            select(File).where(
                File.project_id == project_id,
                File.path == path
            )
        )
        return result.scalar_one_or_none()
    
    @staticmethod
    async def update_file(
        db: AsyncSession,
        file_id: str,
        content: str,
        user_id: str
    ) -> Optional[File]:
        """
        更新文件
        
        更新文件内容
        """
        # 获取文件
        result = await db.execute(select(File).where(File.id == file_id))
        file = result.scalar_one_or_none()
        
        if not file:
            return None
        
        # 更新文件
        file.content = content
        file.updated_by = user_id
        file.updated_at = datetime.utcnow()
        
        await db.commit()
        await db.refresh(file)
        
        return file
    
    @staticmethod
    async def delete_file(
        db: AsyncSession,
        file_id: str
    ) -> bool:
        """
        删除文件
        
        通过ID删除文件
        """
        result = await db.execute(select(File).where(File.id == file_id))
        file = result.scalar_one_or_none()
        
        if not file:
            return False
        
        await db.delete(file)
        await db.commit()
        
        return True
    
    @staticmethod
    async def list_files(
        db: AsyncSession,
        project_id: str
    ) -> List[File]:
        """
        列出文件
        
        获取项目中的所有文件
        """
        result = await db.execute(
            select(File).where(File.project_id == project_id)
        )
        return result.scalars().all()